package com.sanweibook.jhook.web.sys;

import com.sanweibook.jhook.autocode.GeneratorProcessor;
import com.sanweibook.jhook.autocode.param.GeneratorParam;
import com.sanweibook.jhook.common.result.Result;
import com.sanweibook.jhook.web.sys.vo.GeneratorVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by twg on 17/3/22.
 */
@Slf4j
@Controller
@RequestMapping("/admin/generator")
public class GeneratorController {

    @Autowired
    private GeneratorProcessor generatorProcessor;

    @RequestMapping
    public String index() {
        return "generator";
    }

    @RequestMapping("generate")
    @ResponseBody
    public Result<String> generateFile(@RequestBody @Valid GeneratorVO generatorVO, BindingResult bindingResult) {
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            return Result.returnErrorResult("00000",fieldError.getDefaultMessage());
        }
        GeneratorParam generatorParam = new GeneratorParam();
        BeanUtils.copyProperties(generatorVO,generatorParam);
        try {
            generatorProcessor.execute(generatorParam);
            return Result.returnSuccessResult("文件生成成功");
        }catch (Exception e){
            log.error("code generate is error.",e);
        }
        return Result.returnErrorResult("00000","文件生成失败");
    }


}
